package br.com.abril.sforce;

import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import br.com.abril.profile.Preferences;
import br.com.abril.sforce.SalesForceProfile.ProfileStatus;

@Service
public class SalesForceProfileService {
	
	@Autowired
	private SalesForceProfileRepository repository;
	
	@Autowired
	private Preferences preferences;

	@Autowired
	private ProxyChangedEventPublisher proxyChangedEventPublisher;
	
	private SalesForceProfile cachedProfile;
	
	
	private ProxyProvider proxyProvider;
	
	
	
	public SalesForceProfileService() {
		
	}

	@PostConstruct
	public void init() {
		
		proxyProvider = new ProxyProvider(preferences);
		
		loadSalesForceProfile();
	
	}
	
	public SalesForceProfileRepository getRepository() {
		return repository;
	}
	
	public SalesForceProfile getOne() {
		List<SalesForceProfile> profiles = repository.findByStatus(SalesForceProfile.ProfileStatus.ENABLED);
		if (profiles.isEmpty()) return null;
		return profiles.get(0);
	}
	
	public void loadSalesForceProfile() {
		this.cachedProfile = getOne();
	}
	
	public SalesForceProfile getCachedProfile() {
		return cachedProfile;
	}
	
	public ProxyProvider getProxyProvider() {
		return proxyProvider;
	}
	
	
	public void notifyProxyIsChanged() {
		proxyChangedEventPublisher.publish();
	}
	
	@Transactional(readOnly=true)
	public List<SalesForceProfile> findAll() {
		return repository.findAll();
	}
	
	@Transactional
	public void save (SalesForceProfile profile) {
		repository.disableAllProfiles();
		profile.setStatus(ProfileStatus.ENABLED);
		repository.save(profile);
		loadSalesForceProfile();
		notifyProxyIsChanged();
	}
	
	public Preferences getPreferences() {
		return preferences;
	}
	
}
